package zheezes.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author hcconquer@gmail.com
 */
public class ZString {
	public static InputStream getInputStream(String str) {
		if (str == null) {
			return null;
		}
		return new ByteArrayInputStream(str.getBytes());
	}
	
	public static String toString(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		return new String(bytes);
	}
	
	/**
	 * @param str
	 *         the string to trim
	 * @param table
	 *         the trim char table
	 * @return
	 *         trimed string
	 */
	public static String trim(String str, char[] table) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (ZArray.find(table, c) >= 0) {
				continue;
			}
			sb.append(c);
		}
		return sb.toString();
	}
	
	/**
	 * extend the String.split
	 * split string by some string
	 * 
	 * @param str
	 *         the string to split
	 * @param sps
	 *         the split match table
	 * @return
	 *         splitted string array
	 */
	public static String[] split(String str, String[] sps) {
		List<String> list = new ArrayList<String>();
		int begin = 0, next = -1;
		while (begin < str.length()) {
			int jump = 0;
			for (String sp : sps) {
				next = str.indexOf(sp, begin);
				if (next > 0) {
					jump = sp.length();
					break;
				}
			}
			if (next < 0) {
				list.add(str.substring(begin));
				break;
			}
			list.add(str.substring(begin, next));
			begin = next + jump;
			next = -1;
		} // while
		return list.toArray(new String[0]);
	}
	
	public static int find(String[] array, String key) {
		return ZArray.find(array, key, new Comparator<String>() {
			@Override
			public int compare(String p, String q) {
				return p.compareTo(q);
			}
		});
	}
	
	public static int findIngoreCase(String[] array, String key) {
		return ZArray.find(array, key, new Comparator<String>() {
			@Override
			public int compare(String p, String q) {
				return p.compareToIgnoreCase(q);
			}
		});
	}
	
	public static void main(String[] args) {
		String[] ss = split("abc;def.kef", new String[] { ";", "." });
		System.out.println(ss.length);
		for (String s: ss) {
			System.out.println(s);
		}
	}
}
